package com.ccnf.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Slf4j
public class WebLogFilter extends OncePerRequestFilter {
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (!pathMatcher.match("/actuator/**", requestURI) && !pathMatcher.match("/druid/**", requestURI)) {
            String requestInfo = "[" + request.getMethod() + "] " + requestURI;
            log.info("==> " + requestInfo);

            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
            if (entries.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, String[]> entry : entries) {
                    String[] value = entry.getValue();
                    String value1 = value[0] != null ? value[0].toString() : "null";
                    sb.append(entry.getKey() + "=" + value1 + ", ");
                }
                String params = sb.toString();
                log.info("==> request parameters: " + params.substring(0, params.length() - 2));
            }
        }
        chain.doFilter(request, response);
    }
}